package com.android.equipment.ui.model

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import com.android.equipment.base.BaseActivity
import com.android.equipment.config.Constant
import com.android.equipment.dao.DeviceModel
import com.android.equipment.dao.operate.DaoConfigModel
import com.android.equipment.dao.operate.DaoDeviceModel
import com.android.equipment.databinding.ActivityEditDeviceModelBinding
import com.android.equipment.utils.ToastUtil
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.OnTitleBarListener
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions
import com.luck.picture.lib.utils.DateUtils
import com.lxj.xpopup.XPopup


class EditDeviceModelActivity: BaseActivity<ActivityEditDeviceModelBinding>() {
    private var id: Long = 0
    //private var isEdit = false
    lateinit var currentDeviceModel: DeviceModel
    private val REQUEST_CODE_SCAN_ONE = 0X01
    override fun setLayoutContent(): ActivityEditDeviceModelBinding {
        return ActivityEditDeviceModelBinding.inflate(layoutInflater)
    }

    override fun initView(savedInstanceState: Bundle?) {
        id = intent.getLongExtra("id", 0L)
        //isEdit = id > 0L
    }

    override fun initData() {
        binding.mTitleBar.setTitle("型号修改")
        binding.tvSubmit.text = "确认修改"
        val deviceModel = DaoDeviceModel.getInstance().getDeviceModel(id)
        currentDeviceModel = deviceModel
        setDeviceModelInfo()

    }

    override fun initEvent() {
        super.initEvent()
        binding.mTitleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(v: View?) {
                mSwipeBackHelper.backward()
            }

            override fun onTitleClick(v: View?) {

            }

            override fun onRightClick(v: View?) {

            }

        })

        // 必须在事件发生前，调用这个方法来监视View的触摸
        val builder = XPopup.Builder(this)
            .watchView(binding.tvProtocol)
        binding.tvProtocol.setOnClickListener {
            builder.asAttachList(Constant.protocolList.toTypedArray(), null) { position, text ->
                binding.tvProtocol.text = text
                currentDeviceModel.protocol = position
            }
                .show()
        }

        binding.tvSubmit.setOnClickListener {
            if (checkCurrentDeviceModel()){
                currentDeviceModel.updateTime = DateUtils.getYearDataFormat(System.currentTimeMillis())
                DaoDeviceModel.getInstance().updateDeviceModel(currentDeviceModel)
                mSwipeBackHelper.backward()
//                if (isEdit){
//
//                }else{
//                    currentDeviceModel.createTime = DateUtils.getYearDataFormat(System.currentTimeMillis())
//                    val deviceModelId = DaoDeviceModel.getInstance().addDeviceModel(currentDeviceModel)
//
//                    DaoConfigModel.getInstance().addDefaultConfigModel(deviceModelId)
//                    mSwipeBackHelper.backward()
//                }
            }

        }

        binding.ivScan.setOnClickListener{
            XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.READ_MEDIA_IMAGES)
                .permission(Permission.READ_MEDIA_AUDIO)
                .permission(Permission.READ_MEDIA_VIDEO)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            //部分获取成功
                            XXPermissions.startPermissionActivity(mContext!!, permissions)
                            return
                        }


                        ScanUtil.startScan(
                            this@EditDeviceModelActivity,
                            REQUEST_CODE_SCAN_ONE,
                            HmsScanAnalyzerOptions.Creator().create()
                        )
                    }

                    override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                        if (doNotAskAgain) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(mContext!!, permissions)
                        } else {
                            ToastUtil.showToastSafe("获取权限失败！")
                        }
                    }
                })
        }
    }


    private fun checkCurrentDeviceModel(): Boolean{
        if (binding.etModelName.text.toString().isEmpty()){
            ToastUtil.showToastSafe("请输入设备型号！")
            return false
        }
        if (binding.etModelCode.text.toString().isEmpty()){
            ToastUtil.showToastSafe("请输入设备编码")
            return false
        }
        if (binding.etPrefix.text.toString().isEmpty()){
            ToastUtil.showToastSafe("四码前缀不可为空")
            return false
        }
        currentDeviceModel.deviceModel = binding.etModelName.text.toString()
        currentDeviceModel.modelCode = binding.etModelCode.text.toString()
        currentDeviceModel.prefix = binding.etPrefix.text.toString()
        return true
    }

    private fun setDeviceModelInfo() {
        binding.etModelName.setText(currentDeviceModel.deviceModel)
        binding.etModelCode.setText(currentDeviceModel.modelCode)
        binding.etPrefix.setText(currentDeviceModel.prefix)
        binding.tvProtocol.text = Constant.protocolList[currentDeviceModel.protocol]
    }

    override fun setStatusBar() {
        super.setStatusBar()
        ImmersionBar.with(this)
            .fullScreen(true)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || data == null) {
            return
        }
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            val obj: HmsScan? = data.getParcelableExtra(ScanUtil.RESULT)
            //val obj: HmsScan? = data.getParcelableExtra(ScanUtil.RESULT, HmsScan::class.java)
            if (obj != null) {
                val value: String = obj.originalValue
                binding.etModelCode.setText(value)

            }
        }
    }
}